<template>
  <div class="art-full-height area-detail-container">
    <ElCard class="art-table-card" shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="flex items-center gap-4">
            <ElButton @click="goBack" :icon="ArrowLeft">返回</ElButton>
            <h2>小区详情</h2>
          </div>
        </div>
      </template>

      <div class="area-detail-content">
        <ElRow :gutter="20" class="area-detail-row">
          <!-- 左侧：小区详情 -->
          <ElCol :span="8" class="area-info-col">
            <ElCard class="mb-4" shadow="never">
              <template #header>
                <div class="flex justify-between items-center">
                  <span class="font-bold">小区信息</span>
                </div>
              </template>
              
              <ElDescriptions :column="1" border>
                <ElDescriptionsItem label="小区名称" label-width="100px">{{ areaDetail.areaName }}</ElDescriptionsItem>
                <ElDescriptionsItem label="小区地址" label-width="100px">{{ areaDetail.areaAddress }}</ElDescriptionsItem>
                <ElDescriptionsItem label="楼栋数" label-width="100px">{{ areaDetail.areaHouseNum }}栋</ElDescriptionsItem>
                <ElDescriptionsItem label="单元数" label-width="100px">{{ areaDetail.areaUnitNum }}单元</ElDescriptionsItem>
                <ElDescriptionsItem label="显示状态" label-width="100px">
                  <ElTag :type="areaDetail.areaUpFlag === 1 ? 'info' : 'success'">
                    {{ areaDetail.areaUpFlag === 1 ? '隐藏' : '显示' }}
                  </ElTag>
                </ElDescriptionsItem>
                <ElDescriptionsItem label="创建时间" label-width="100px">
                  {{ areaDetail.createTime ? dayjs(areaDetail.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}
                </ElDescriptionsItem>
                <ElDescriptionsItem label="小区介绍" label-width="100px">{{ areaDetail.areaInfo }}</ElDescriptionsItem>
              </ElDescriptions>
              
             <div class="flex gap-8 mt-4 image-section">
              <div class="flex-item">
                <div class="mb-2">小区规划图:</div>
                <div v-if="areaPlanInfo.length > 0" class="flex flex-wrap gap-2">
                  <ElImage
                    v-for="(image, index) in areaPlanInfo"
                    :key="index"
                    :src="image.url"
                    :preview-src-list="areaPlanInfo.map(img => img.url)"
                    preview-teleported
                    fit="cover"
                    class="w-48 h-48"
                  />
                </div>
                <div v-else class="text-gray-500">暂无规划图</div>
              </div>
              
              <div class="flex-item">
                <div class="mb-2">小区图片:</div>
                <div v-if="areaPhoto.length > 0" class="flex flex-wrap gap-2">
                  <ElImage
                    v-for="(image, index) in areaPhoto"
                    :key="index"
                    :src="image.url"
                    :preview-src-list="areaPhoto.map(img => img.url)"
                    preview-teleported
                    fit="cover"
                    class="w-48 h-48"
                    />
                </div>
                <div v-else class="text-gray-500">暂无图片</div>
              </div>
            </div>
              
              <div class="mt-4">
                <div class="mb-2">服务内容:</div>
                <div class="border border-gray-300 rounded p-3 min-h-12">
                  <div v-if="areaDetail.geoAreaServeList && areaDetail.geoAreaServeList.length > 0">
                    <ElTag
                      v-for="(service, index) in areaDetail.geoAreaServeList"
                      :key="index"
                      class="m-1"
                      >
                      {{ service.serveName }}
                    </ElTag>
                  </div>
                  <div v-else class="text-gray-500">暂无服务内容</div>
                </div>
              </div>
            </ElCard>
          </ElCol>
          
          <!-- 右侧：小区员工 -->
          <ElCol :span="16" class="area-staff-col">
            <ElCard shadow="never" class="area-staff-card">
              <template #header>
                <div class="flex justify-between items-center">
                  <span class="font-bold">小区员工</span>
                  <ElButton type="primary" :icon="Plus" @click="handleAddUser">新增员工</ElButton>
                </div>
              </template>
              
              <div class="area-staff-table-container">
                <ArtTable
                  :loading="userLoading"
                  :data="userData"
                  :columns="userColumns"
                  :pagination="userPagination"
                  @pagination:size-change="handleUserSizeChange"
                  @pagination:current-change="handleUserCurrentChange"
                  >
                  <template #employeeGender="{ row }">
                    <ElTag :type="row.employeeGender === 1 ? 'primary' : 'success'">
                      {{ row.employeeGender === 1 ? '男' : '女' }}
                    </ElTag>
                  </template>
                  
                  <template #serveFlag="{ row }">
                    <ElTag :type="row.serveFlag === 2 ? 'success' : 'info'">
                      {{ row.serveFlag === 2 ? '是' : '否' }}
                    </ElTag>
                  </template>
                  
                  <template #operation="{ row }">
                    <div class="flex items-center gap-2">
                      <ArtButtonTable type="delete" @click="handleDeleteUser(row)">删除</ArtButtonTable>
                    </div>
                  </template>
                </ArtTable>
              </div>
            </ElCard>
          </ElCol>
        </ElRow>
      </div>
    </ElCard>
    
    <!-- 添加小区用户弹窗 -->
    <ElDialog
      v-model="addUserDialogVisible"
      title="添加小区用户"
      width="500px"
      >
      <ElForm
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserFormRules"
        label-width="100px"
        >
        <ElFormItem label="服务内容" prop="serveName">
          <ElInput
            v-model="addUserForm.serveName"
            placeholder="请输入服务内容"
            />
        </ElFormItem>
        
        <ElFormItem label="服务提供" prop="serveFlag">
          <ElRadioGroup v-model="addUserForm.serveFlag">
            <ElRadio :value="2">是</ElRadio>
            <ElRadio :value="1">否</ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        
        <ElFormItem label="用户" prop="userId">
          <ElSelect
            v-model="addUserForm.userId"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="getUserList"
            :loading="userListLoading"
            style="width: 100%"
            >
            <ElOption
              v-for="item in userList"
              :key="item.id"
              :label="`${item.newName} (${item.newPhone})`"
              :value="item.id"
              />
          </ElSelect>
        </ElFormItem>
      </ElForm>
      
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="handleCancelAddUser">取消</ElButton>
          <ElButton type="primary" @click="submitAddUserForm">确定</ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { dayjs, ElMessage, ElMessageBox, ElForm, FormRules } from 'element-plus'
  import { ArrowLeft, Plus } from '@element-plus/icons-vue'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import {
    geoAreaGetDataUsingPost,
    geoAreaUserPageDataUsingPost,
    geoAreaUserSaveDataUsingPost,
    geoAreaUserDeleteDataUsingPost,
    openApiNewUserPageDataUsingPost,
    GeoAreaVo
  } from '@/api'

  const route = useRoute()
  const router = useRouter()

  // 小区详情数据
  const areaDetail = ref<GeoAreaVo>({
    areaName: '',
    areaAddress: '',
    areaLongitude: '',
    areaLatitude: '',
    areaHouseNum: 0,
    areaUnitNum: 0,
    areaUpFlag: 2,
    areaInfo: '',
    areaPlanInfo: '',
    areaPhoto: '',
    geoAreaServeList: [],
    createTime: ''
  })

  const areaPlanInfo = ref<any[]>([])
  const areaPhoto = ref<any[]>([])

  // 小区员工数据
  const userLoading = ref(false)
  const userData = ref<any[]>([])
  const userPagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })

  // 添加用户表单
  const addUserDialogVisible = ref(false)
  const addUserFormRef = ref<InstanceType<typeof ElForm>>()
  const addUserForm = reactive({
    serveName: '',
    serveFlag: 2,
    userId: null as number | null
  })

  const addUserFormRules: FormRules = {
    serveName: [{ required: true, message: '请输入服务内容', trigger: 'blur' }],
    serveFlag: [{ required: true, message: '请选择服务提供', trigger: 'change' }],
    userId: [{ required: true, message: '请选择用户', trigger: 'change' }]
  }

  // 用户列表（添加用户时使用）
  const userList = ref<any[]>([])
  const userListLoading = ref(false)

  // 员工表格列配置
    const userColumns = [
      {
        prop: 'employeeName',
        label: '员工名称',
        width: 120,
        formatter: (row: any) => row.userIdVo?.employeeName || ''
      },
      {
        prop: 'employeeGender',
        label: '性别',
        width: 80,
        align: 'center',
        headerAlign: 'center',
        useSlot: true
      },
      {
        prop: 'employeePhone',
        label: '手机号码',
        width: 120,
        formatter: (row: any) => row.userIdVo?.employeePhone || ''
      },
    {
      prop: 'serveName',
      label: '服务内容',
      width: 120
    },
    {
      prop: 'serveFlag',
      label: '服务提供',
      width: 100,
      align: 'center',
      headerAlign: 'center',
      useSlot: true
    },
    {
      prop: 'createTime',
      label: '创建时间',
      align: 'center',
      headerAlign: 'center',
      formatter: (row: any) => row.createTime ? dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    {
      prop: 'operation',
      label: '操作',
      width: 100,
      fixed: 'right',
      align: 'center',
      headerAlign: 'center',
      useSlot: true
    }
  ]

  // 返回上一页
  const goBack = () => {
    router.go(-1)
  }

  // 获取小区详情
  const getAreaDetail = async () => {
    try {
      const areaId = route.query.areaId as string
      if (!areaId) {
        ElMessage.error('缺少小区ID参数')
        return
      }

      const res = await geoAreaGetDataUsingPost({
        body: { id: parseInt(areaId) }
      })

      if (res) {
        areaDetail.value = res as GeoAreaVo
        areaPlanInfo.value = JSON.parse(res.areaPlanInfo || '[]')
        areaPhoto.value = JSON.parse(res.areaPhoto || '[]')
      } else {
        ElMessage.error('未找到小区信息')
      }
    } catch (error) {
      console.error('获取小区详情失败:', error)
      ElMessage.error('获取小区详情失败: ' + (error as Error).message)
    }
  }

  // 获取小区员工列表
  const getUserListData = async () => {
    try {
      userLoading.value = true
      const areaId = route.query.areaId as string
      if (!areaId) {
        ElMessage.error('缺少小区ID参数')
        userLoading.value = false
        return
      }

      const res = await geoAreaUserPageDataUsingPost({
        body: {
          areaId: parseInt(areaId),
          current: userPagination.current,
          size: userPagination.size
        }
      })

      if (res) {
        userData.value = res.list || []
        userPagination.total = res.total || 0
      }
    } catch (error) {
      console.error('获取小区员工列表失败:', error)
      ElMessage.error('获取小区员工列表失败: ' + (error as Error).message)
    } finally {
      userLoading.value = false
    }
  }

  // 分页相关方法
  const handleUserSizeChange = (val: number) => {
    userPagination.size = val
    getUserListData()
  }

  const handleUserCurrentChange = (val: number) => {
    userPagination.current = val
    getUserListData()
  }

  // 获取用户列表（添加用户时搜索）
  const getUserList = async (keyword = '') => {
    userListLoading.value = true
    try {
      const params = {
        current: 1,
        size: 20,
        newPhone: keyword
      }

      const res = await openApiNewUserPageDataUsingPost({ body: params })

      if (res.list) {
        userList.value = res.list
      }
    } catch (error) {
      ElMessage.error('获取用户列表失败')
    } finally {
      userListLoading.value = false
    }
  }

  // 添加用户相关方法
  const handleAddUser = () => {
    addUserDialogVisible.value = true
    getUserList()
  }

  const handleCancelAddUser = () => {
    addUserDialogVisible.value = false
    addUserFormRef.value?.resetFields()
    Object.assign(addUserForm, {
      serveName: '',
      serveFlag: 1,
      userId: null
    })
  }

  const submitAddUserForm = async () => {
    if (!addUserFormRef.value) return

    await addUserFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const areaId = route.query.areaId as string
          if (!areaId) {
            ElMessage.error('缺少小区ID参数')
            return
          }

          const response = await geoAreaUserSaveDataUsingPost({
            body: {
              areaId: parseInt(areaId),
              serveName: addUserForm.serveName,
              serveFlag: addUserForm.serveFlag,
              userId: addUserForm.userId!
            }
          })

          ElMessage.success('添加成功')
          handleCancelAddUser()
          getUserListData()
        } catch (error) {
          console.error('添加小区用户失败:', error)
          ElMessage.error('添加失败: ' + (error as Error).message)
        }
      }
    })
  }

  // 删除用户
    const handleDeleteUser = async (row: any) => {
      try {
        await ElMessageBox.confirm(`确定要删除用户"${row.userIdVo?.employeeName || ''}"吗？`, '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const areaId = route.query.areaId as string
        if (!areaId) {
          ElMessage.error('缺少小区ID参数')
          return
        }

        const response = await geoAreaUserDeleteDataUsingPost({
          body: {
            areaId: parseInt(areaId),
            userId: row.userId  
          }
        })

        ElMessage.success('删除成功')
        getUserListData()
      } catch {
        // 用户取消删除
      }
    }

  // 更多操作方法
  const handleMore = (row: any) => {
    ElMessage.info('更多操作功能待实现')
  }

  onMounted(() => {
    getAreaDetail()
    getUserListData()
  })

  // 监听路由变化，当用户直接访问不同小区详情页时重新加载数据
  watch(
    () => route.query.areaId,
    (newId, oldId) => {
      if (newId && newId !== oldId) {
        getAreaDetail()
        getUserListData()
      }
    }
  )
</script>

<style lang="scss" scoped>
  .area-detail-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .area-detail-content {
    flex: 1;
    overflow: auto;
  }

  .area-detail-row {
    flex-wrap: nowrap;
  }

  .area-info-col,
  .area-staff-col {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .area-staff-card {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .area-info-col :deep(.el-card) {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  
  .area-info-col :deep(.el-card__body) {
    flex: 1;
    overflow: auto;
  }

  .area-staff-table-container {
    flex: 1;
    overflow: auto;
    max-height: 600px; 
  }

  .image-section {
    display: flex;
    gap: 2rem;
  }
  
  .flex-item {
    flex: 1;
  }

  @media (max-width: 1200px) {
    .area-detail-row {
      flex-direction: column;
    }
    
    .area-info-col,
    .area-staff-col {
      width: 100% !important;
      max-width: 100%;
    }
    
    :deep(.el-col) {
      width: 100% !important;
      max-width: 100% !important;
    }
    
    .area-info-col :deep(.el-card),
    .area-staff-card {
      height: auto;
    }
  }

  @media (max-width: 1680px) {
    .image-section {
      flex-direction: column;
      gap: 1rem;
    }
    
    .flex-item:not(:last-child) {
      margin-bottom: 1rem;
    }
    
    .image-section .flex-item {
      width: 100%;
    }
  }

  .service-tag {
    margin: 2px;
  }
</style>